//函数的注释看ts类型，鼠标悬浮在ts类型上即可查看注释


export const myForEach: Array<any>['myForEach'] = function (this, callbackfn) {
    if (!callbackfn) return
    for (let i = 0; i < this.length; i++) {
        callbackfn(this[i], i, this)
    }
}

export const myFlat: Array<any>['myFlat'] = function (this, depth = 1) {
    let res: any[] = []
    if (depth <= 0) return this //如果要降低的维度不合理，直接返回原数组
    for (const item of this) {
        if (Array.isArray(item)) {//如果是数组的话，进行递归。
            res = res.concat(myFlat.call(item, depth - 1)) //这里使用concat，链接递归返回的数据
        } else {
            item !== undefined && res.push(item) //如果不为空，才放入结果数组
        }
    }
    return res

    //方法二
    // if (n <= 0) return arr //如果要降低的维度不合理，直接返回原数组
    // const res = flat(arr, n - 1)
    // return [].concat(...res)
}

export const myMap: Array<any>['myMap'] = function (this, callbackfn) {
    if (!callbackfn) return []
    const res: any[] = []
    for (let i = 0; i < this.length; i++) {
        res.push(callbackfn(this[i], i, this))
    }
    return res
}

export const myFilter: Array<any>['myFilter'] = function (this, callbackfn) {
    if (!callbackfn) return []
    const res: any[] = []
    for (let i = 0; i < this.length; i++) {
        if (callbackfn(this[i], i, this)) {
            res.push(this[i])
        }
    }
    return res
}

export const myReduce: Array<any>['myReduce'] = function (this, callbackfn, initialValue) {
    if (!callbackfn) return

    //如果没有传递初始值，那么pre会是数组的第0个元素，cur是数组第1个元素（也就是从1开始遍历）

    /**上一个的值，最后会作为最终结果返回出去 */
    let pre: any
    /**起始遍历位置。 */
    let start: number

    if (initialValue !== undefined) {  //如果传递了初始值，就是正常的从0开始遍历
        pre = initialValue
        start = 0
    } else { //没传递就从1开始遍历，pre初始值为数组第0个元素
        pre = this[0]
        start = 1
    }


    for (let i = start; i < this.length; i++) {
        pre = callbackfn(pre, this[i], i, this)
    }

    return pre
}

export const myFill: Array<any>['myFill'] = function (this, value, start = 0, end = this.length - 1) {
    for (let i = start; i <= end; i++) {
        this[i] = value;
    }
    return this
}

export const myIncludes: Array<any>['myIncludes'] = function (this, searchElement, fromIndex = 0) {
    if (fromIndex < 0) fromIndex = this.length + fromIndex //参数小于0时
    for (let i = fromIndex; i < this.length; i++) {
        if (this[i] === searchElement) return true
    }
    return false
}

export const myJoin: Array<any>['myJoin'] = function (this, separator = ',') {
    let res = ''
    for (let i = 0; i < this.length; i++) {
        const element = this[i];
        if (element != undefined) {
            res += element + (i === this.length - 1 ? '' : separator) //最后一个不用加
        } else {
            res += separator
        }
    }
    return res
}